<?php

namespace App\Admin\Actions\CollectionAction;

use App\Models\User;
use Brick\Math\RoundingMode;
use Illuminate\Http\Request;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Actions\RowAction;
use App\Supports\Withdraw\Withdrawer;
use Illuminate\Database\Eloquent\Model;
use App\Models\Collection;
use App\Models\GcUserImage;
use App\Models\GcText;


class DistributeUser extends RowAction
{
	public $name = '分配用户';

	public function handle(Model $model, Request $request)
	{
		/*if (!in_array(Admin::user()->id, [1,3])) {
			return $this->response()->error('无权操作')->refresh();
		}*/

		/**
		 * @var User $user
		 */

		
		$gcType = $request->get('gc_type', 0);

		if (!in_array($gcType, ['xhs', 'dy','sph','ks'])) {
			return $this->response()->error('请选择渠道');
		}

		$arr = [];
		$gcUserImage = GcUserImage::query()->where('gc_group_id',$model->id)->where('gc_type',$gcType)->where('is_used',false)->where("user_id",0)->select('id','gc_category_id')->get();

		if(empty($gcUserImage->toArray())){
			return $this->response()->error('该渠道暂无可分配图文');

		}

		$gcCategoryUserImage = [];
		foreach($gcUserImage->toArray() as $k=>$v){

			$gcCategoryUserImage[$v['gc_category_id']][] = $v['id'];
		}
		
		//$gcCategoryUserImage = array_column($gcUserImage->toArray(), 'id','gc_category_id');
		
		
		$field = $gcType."_num";
		$users = User::where('gc_group_id',$model->id)->where($field,">",0)->where('gc_category_id',">",0)->where('is_locked',false)->get();
		

		$i = 0;
		$updateData = [];
		foreach($users as $k=>$v){
			$count = $v->gcUserImage->where('is_used',false)->count();
			

			$canDistributeCount = $v->$field - $count;
			for($j=0;$j<$canDistributeCount;$j++){
				
				if(isset($gcCategoryUserImage[$v->gc_category_id]) && !empty($gcCategoryUserImage[$v->gc_category_id])){

					$updateData[$i]['id'] = $gcCategoryUserImage[$v->gc_category_id][0];
					$updateData[$i]['user_id'] =  $v->id;
					array_shift($gcCategoryUserImage[$v->gc_category_id]);


					$i++;
				}
				
			}

		}

		if(empty($updateData)){

			return $this->response()->error('该渠道暂无可分配用户');
		}

		GcUserImage::updateBatch($updateData);
		
		

		

		return $this->response()->success('用户已分配至分配管理系统中')->refresh();
	}

	public function form()
	{
		$this->select('gc_type', '渠道')
            ->options(config("site.gcType"));

		
	}
}
